package cn.swust.score.controller;

 
import java.io.IOException;
import java.util.List; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid; 
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.validation.annotation.Validated; 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; 
import com.github.pagehelper.PageInfo; 
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.swust.score.basepojo.ResultResponse; 
import cn.swust.score.pojo.QueryRater;
import cn.swust.score.pojo.Rater;
import cn.swust.score.service.RaterService;
import cn.swust.score.util.FileUtil;
import cn.swust.score.util.GetPinyin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "评分人信息")
@RestController
@Validated
@RequestMapping("/rater")
public class RaterController {
	
	@Value("${files.path}")
	private String filesPath;
	@Autowired
	public  RaterService raterService;
	
	@ApiOperation(value="删除记录")
	@PostMapping(value="/del")
	public ResultResponse<Integer> delById(
	@ApiParam(required=true,value="查询记录编号") @RequestBody Rater record) {
		return new ResultResponse<Integer>( raterService.delById(record.getId()));
	}
	

	@ApiOperation(value="新增记录")
	@PostMapping(value="/add")
	@ApiParam(required = true, value = "记录值")
	// @RequestBody是作用在形参列表上，用于将前台发送过来固定格式的数据【xml 格式或者 json等】
	//封装为对应的 JavaBean 对象，封装时使用到的一个对象是系统默认配置的 HttpMessageConverter进行解析，
	//然后封装到形参上。
	//@Valid 校验Rater 里面的参数，比如不为空max，size(min,max)等
	public ResultResponse<Rater> save(@Valid  @RequestBody Rater record) {
		String num = GetPinyin.getPingYin(record.getName());
		record.setNumber(num);
		record.setPassword("000000");
	    if(raterService.save(record)<=0)
	        record=null;
	    else
	        record=raterService.getById(record.getId());
		return new ResultResponse<Rater>(record);
	}
	

	@ApiOperation(value = "根据ID查询记录") 
	@PutMapping(value = "/get")
	public ResultResponse<Rater> getById(
			@ApiParam(required = true, value = "查询记录编号")
			@RequestBody @Valid Integer id) {
		Rater rater = raterService.getById(id);
		return new ResultResponse<Rater>(rater);
	}

	@ApiParam(required = true , value = "记录内容")
	@PostMapping(value = "/edit") 
	public ResultResponse<Rater> editById(@Valid @RequestBody Rater record) {
		String num = GetPinyin.getPingYin(record.getName());
		record.setNumber(num);
		if(raterService.edit(record)<=0)
	        record=null;
	    else
	        record=raterService.getById(record.getId());
		return new ResultResponse<Rater>(record);
	}

	@ApiOperation(value = "详细列表查询") 
	@PostMapping("/listpage")
	public ResultResponse<PageInfo<Rater>> listpage
			(@ApiParam(required = false, value = "查询参数")
			@Valid @RequestBody QueryRater param) {
		 return new  ResultResponse<PageInfo<Rater>>(raterService.list(param.getPageNum(),param.getPageSize(),param));
	}

	
	@ApiOperation(value = "详细列表查询")
	@PostMapping("/list")
	public ResultResponse<List<Rater>> list(
			@ApiParam(required = false, value = "查询参数") @Valid @RequestBody QueryRater param) {
		return new ResultResponse<List<Rater>>(
				raterService.list(param));
	}

	@ApiOperation(value = "导出excel")
	@GetMapping("/excel")
	public void  excel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int scoreInfoId = Integer.parseInt(request.getParameter("scoreInfoId")); 
		QueryRater qc = new QueryRater();
		qc.setscoreInfoId(scoreInfoId);
		
		PageInfo<Rater> listData =raterService.list(0, 0, qc);

		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Rater.class, listData.getList());

		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=评分人.xls");
		workbook.write(response.getOutputStream());
	}

	@ApiOperation(value = "导入excel")
	@PostMapping("/import")
	public ResultResponse<String> importExcel(@ApiParam(required = false, value = "导入文件") @Valid MultipartFile file)
			throws IOException, Exception {
		String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("Lack of suffix name.");
		}
		String md5 = FileUtil.fileMd5(file.getInputStream());
		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		//String prefix = fileOrigName.substring(fileOrigName.lastIndexOf(".") + 1);
		String pathname = FileUtil.getPath() + md5 + fileOrigName;
		String fullPath = filesPath + pathname;
		FileUtil.saveFile(file, fullPath);
		ImportParams params = new ImportParams();
		// params.setTitleRows(1);
		params.setHeadRows(1);

		List<Rater> personList = ExcelImportUtil.importExcel(file.getInputStream(), Rater.class, params);

		for(int i = 0; i< personList.size(); i++)
		{
			String num = GetPinyin.getPingYin(personList.get(i).getName());
			personList.get(i).setNumber(num);
		}
		raterService.save(personList);
		return new ResultResponse<String>(0, "OK", file.getOriginalFilename());
	}
	
}
